#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from hashlib import sha256

from typing import  List

from email_validator import validate_email, EmailNotValidError
from fast_captcha import text_captcha
from fastapi import Request, HTTPException, Response, UploadFile
from fastapi.security import OAuth2PasswordRequestForm
from fastapi_pagination.ext.async_sqlalchemy import paginate
from loguru import logger

from sqlalchemy.ext.asyncio import AsyncSession

from app.api import jwt
from app.common.exception import errors
from app.common.log import log
# from backend.app.common.redis import redis_client
from app.common.response.response_code import CodeEnum
from app.core.conf import ST
from app.core.path_conf import AvatarPath
from app.crud import crud_user
from app.crud import crud_project
from app.database.db_sqlite import async_db_session
from app.models import User
from app.models import Project
from app.schemas.user import CreateUser, ResetPassword, UpdateUser, ELCode, Auth2
from app.schemas.project import StartProjectTimer,CreateProjectTimerDao,ProjectWithUserInfo
from app.utils import re_verify
from app.utils.format_string import cut_path
from app.utils.generate_string import get_current_timestamp, get_uuid
from app.utils.send_email import send_verification_code_email, SEND_EMAIL_LOGIN_TEXT

from app.api.service import user_service



async def create_workhour_project(obj: StartProjectTimer):
    async with async_db_session.begin() as db:
        # 检查项目名称是否重复
        project = await crud_project.get_project_by_name(db,obj.name)
        if project:
            raise errors.ForbiddenError(msg='项目名称重复')
        # 根据alias查询用户id,将id更新到obj里面
        username = await crud_user.get_user_by_loginid(db, obj.loginid)
        obj_dict = obj.dict()
        obj_dict.update({'user_id':username.id})
        obj_dict.pop('loginid')
        # 调用dao层,添加数据
        await crud_project.create_project(db,obj_dict)


        # if username:
        #     raise errors.ForbiddenError(msg='该用户名已注册')
        # email = await crud_user.check_email(db, obj.email)
        # if email:
        #     raise errors.ForbiddenError(msg='该邮箱已注册')
        # try:
        #     validate_email(obj.email, check_deliverability=False).email
        # except EmailNotValidError:
        #     raise errors.ForbiddenError(msg='邮箱格式错误')
        # await crud_user.create_user(db, obj)




    




         


async def get_workhour_project_by_user(user:User):
    """通过用户的信息,获取该用户名下,及其下属,所有的工时管理项目

    Args:
        user (User): _description_

    Returns:
        _type_: _description_
    """
    async with async_db_session.begin() as db:
        all_project = []
        # 查询自己的专案
        projects = await crud_project.get_project_by_user_id(db,user.id)
        new_projects = add_user_info_to_projects(projects,user)
        all_project.extend(new_projects)

        # 查询下属的专案
        all_employee = await user_service.get_employees_by_loginid(db,user.loginid)
        # 遍历下属的专案
        for employee in all_employee:
            projects = await crud_project.get_project_by_user_id(db,employee.id)
            new_projects = add_user_info_to_projects(projects,employee)
            all_project.extend(new_projects)

        return all_project

                
        
       
def add_user_info_to_projects(projects:List[Project],user:User)->List[ProjectWithUserInfo]:
    """批量向工时专案中添加用户信息

    Args:
        projects (List[Project]): _description_
        user (User): _description_

    Returns:
        ProjectWithUserInfo: _description_
    """
    all_project = []
    for project in projects:
        project_with_user_info = add_user_info_to_project(project,user)
        all_project.append(project_with_user_info)
    return all_project
        

def add_user_info_to_project(project:Project,user:User)->ProjectWithUserInfo:
    """向工时项目中添加用户信息

    Args:
        project (Project): 向工时项目中添加用户信息,具体包括用户姓名,登录id
        user (User): _description_

    Returns:
        ProjectWithUserInfo: _description_
    """
    attrs = vars(project)
    attrs.update({'loginid':user.loginid,'user_name':user.emp_name})
    # 重新组合需要返回的数据,增加一些属性,会自动过滤结构出来多余的属性,这个好处还是真的好
    res = ProjectWithUserInfo(**attrs)
    return res